package org.example;

import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.AbstractSubProtocolEvent;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;

@Component
public class StompHeartbeatMonitor {

    /// 监听STOMP心跳接收（客户端->服务端）
    @EventListener
    public void handleInboundHeartbeat(SessionConnectedEvent event) {
        System.out.println("in handleInboundHeartbeat event= "+event);
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        if (isHeartbeatMessage(accessor)) {
            System.out.println("[STOMP心跳接收] 会话: " + accessor.getSessionId());
        }
    }

    // 监听STOMP心跳发送（服务端->客户端）
    @EventListener
    public void handleOutboundHeartbeat(SessionSubscribeEvent event) {
        System.out.println("in handleOutboundHeartbeat event= "+event);
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        if (isHeartbeatMessage(accessor)) {
            System.out.println("[STOMP心跳发送] 会话: " + accessor.getSessionId());
        }
    }

    private boolean isHeartbeatMessage(StompHeaderAccessor accessor) {
        return accessor.getCommand() == null &&
                accessor.getHeartbeat() != null &&
                accessor.getMessageHeaders().get("simpMessageType") == SimpMessageType.HEARTBEAT;
    }
}